﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Fcdbas.Core.Net
{
    public class ShareBuffer
    {
        private byte[] buffer;
        private int Start;
        private int End;
        private int BufferSize;
        private object Lock;
        public ShareBuffer(int bufferSize)
        {
            buffer = new byte[bufferSize];
            this.BufferSize = bufferSize;
            Start = 0;
            End = 0;
            Lock = new object();
        }
        public int Write(byte[] write,int offset, int size)
        {
            if (size + (End - Start) > BufferSize)
                throw new Exception("超出缓冲区大小");
            lock (Lock)
            {
                if (size > BufferSize - End)
                {
                    byte[] temp = new byte[End - Start];
                    Buffer.BlockCopy(buffer, Start, temp, 0, temp.Length);
                    Buffer.BlockCopy(temp, 0, buffer, 0, temp.Length);
                    Start = 0;
                    End = temp.Length;
                    Buffer.BlockCopy(write, offset, buffer, End, size);
                    End = End + size;
                }
                else
                {
                    Buffer.BlockCopy(write, offset, buffer, End, size);
                    End += size;
                }
            }
            return End - Start;
        }
        public int Size
        {
            get
            {
                return End - Start;
            }
        }
        public int Read(byte[] read)
        {
            int size = End - Start;
            lock (Lock)
            {
                Buffer.BlockCopy(buffer, Start, read, 0, End - Start);
                Clear();
            }
            return size;
        }
        public void Clear()
        {
            Start = 0;
            End = 0;
        }
    }
}
